#include "stdafx.h"
#include "maprenderer.h"
#include "tilerenderer.h"

#include <glc/shading/phongmaterial.h>
#include <data/map/iglobalmap.hpp>
#include <data/map/globalobjectsarray.hpp>

namespace Graphics {

MapRenderer::MapRenderer()
    :_initialized(false)
{
}

MapRenderer::~MapRenderer()
{
}

void MapRenderer::render(const Data::IGlobalMap &map) const
{
    if (!_initialized) {
        _initialized = true;
        _dlLandscape.begin(false);
        renderLandscape(map);
        _dlLandscape.end();
    } else {
        _dlLandscape.call();
    }
    //renderObjects(map);
}

void MapRenderer::invalidate() const
{
    _initialized = false;
}

void MapRenderer::renderLandscape(const Data::IGlobalMap &map) const
{
    Graphics::TileRenderer renderer;

    GLC::PhongMaterial mat;
    mat.SetAmbient(0.1, 0.1, 0.1);
    mat.SetDiffuse(0.8, 0.8, 0.8);
    mat.SetSpecular(0.1, 0.1, 0.1);
    mat.Activate(GL_FRONT_AND_BACK);
    //glDisable(GL_LIGHTING);
    //glEnable(GL_TEXTURE_2D);
    //glColor3f(1, 1, 1);
    glPushMatrix();
    glTranslatef(-0.5 * map.width(), -0.5 * map.height(), 0);
    for (uint x = 0; x < map.width(); ++x)
    {
        glPushMatrix();
        glTranslatef(x, 0, 0);
        for (uint y = 0; y < map.height(); ++y)
        {
            renderer.render(map.cell(x, y).tile());
            glTranslatef(0, 1, 0);
        }
        glPopMatrix();
    }
    glPopMatrix();

    //glDisable(GL_TEXTURE_2D);
    // glEnable(GL_LIGHTING);
}

void MapRenderer::renderObjects(const Data::IGlobalMap &map) const
{
    {
        GLC::PhongMaterial mat;
        mat.SetAmbient(1, 1, 1);
        mat.SetDiffuse(1, 1, 1);
        mat.SetSpecular(1, 1, 1);
        mat.SetShininess(30);
        mat.Activate(GL_FRONT_AND_BACK);
    }
    glPushMatrix();
    glTranslatef(-0.5 * map.width(), -0.5 * map.height(), 0);
    for (uint x = 0; x < map.width(); ++x) {
        glPushMatrix();
        glTranslatef(x, 0, 0);
        for (uint y = 0; y < map.height(); ++y) {
            const Data::GlobalObjectsArray &ref = map.cell(x, y).objects();
            for (auto it = ref.begin(); it != ref.end(); ++it) {
                //! TODO: implement object rendering
//                Data::IGlobalObject *obj = it->get();
//                obj->render();
            }
            glTranslatef(0, 1, 0);
        }
        glPopMatrix();
    }
    glPopMatrix();
}

} // namespace Graphics
